#include <fstream>
#include <iostream>
#include <filesystem>

#include "serverConfig.h"

namespace fs = std::filesystem;
using namespace std;


ServerConfig* ServerConfig::m_self = nullptr;
mutex ServerConfig::m_selfMutex;
ServerConfig* ServerConfig::instance()
{
    if(m_self == nullptr) {
        lock_guard<mutex> locker(m_selfMutex);
        if(m_self == nullptr)
            m_self = new ServerConfig;
    }
    return m_self;
}

ServerConfig::ServerConfig() : m_sysName("sys.json")
{
    readSysConfig();
}

ServerConfig::~ServerConfig()
{
    if(m_self != nullptr) {
        delete m_self;
        m_self = nullptr;
    }
}

std::string ServerConfig::dataPath()
{
    if(m_sysConfig.contains("dataPath")) {
        return m_sysConfig["dataPath"];
    }
    return "";
}

std::string ServerConfig::userFileName()
{
    if(m_sysConfig.contains("user")) {
        auto u = m_sysConfig["user"];
        if(u.contains("fileName"))
            return u["fileName"];
    }
    return "";
}


void ServerConfig::readSysConfig()
{
    ifstream f(m_sysName);
    if (!f.is_open()) {
        cerr << "open sys config file failed, file name: " << m_sysName << std::endl;
        exit(-1);
    }

    f >> m_sysConfig;
    f.close();
}